import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setUserFromStorage } from '../redux/features/userSlice';
import { getToken, isTokenExpired, getUserInfo as getJwtUserInfo, getUserRoles, hasRole, getUserId } from '../utils/jwtUtils';

/**
 * 认证相关的自定义Hook
 * 提供认证状态、用户信息、角色检查等功能
 */
export const useAuth = () => {
  const dispatch = useDispatch();
  const { isAuthenticated, userInfo, token, isLoading } = useSelector((state) => state.user);
  const [isTokenAboutToExpire, setIsTokenAboutToExpire] = useState(false);

  // 初始化或刷新用户认证状态
  useEffect(() => {
    // 从localStorage同步用户状态到Redux
    dispatch(setUserFromStorage());
  }, [dispatch]);

  // 检查token是否即将过期
  useEffect(() => {
    if (token) {
      setIsTokenAboutToExpire(isTokenExpired(token));
    }

    // 定期检查token是否即将过期（每分钟检查一次）
    const checkInterval = setInterval(() => {
      if (token) {
        setIsTokenAboutToExpire(isTokenExpired(token));
      }
    }, 60000);

    return () => clearInterval(checkInterval);
  }, [token]);

  /**
   * 获取JWT解析后的用户信息
   * @returns {object|null} 解析后的用户信息
   */
  const getParsedUserInfo = () => {
    if (!token) return null;
    return getJwtUserInfo(token);
  };

  /**
   * 获取用户角色
   * @returns {string|array|null} 用户角色
   */
  const getRoles = () => {
    if (!token) return null;
    return getUserRoles(token);
  };

  /**
   * 检查用户是否有指定角色
   * @param {string|array} requiredRoles - 所需角色
   * @returns {boolean} 用户是否有指定角色
   */
  const checkRole = (requiredRoles) => {
    if (!token) return false;
    return hasRole(token, requiredRoles);
  };

  /**
   * 获取用户ID
   * @returns {string|number|null} 用户ID
   */
  const getUserIdFromToken = () => {
    if (!token) return null;
    return getUserId(token);
  };

  /**
   * 检查用户是否已登录
   * @returns {boolean} 用户是否已登录
   */
  const isLoggedIn = () => {
    return isAuthenticated && !!token;
  };

  /**
   * 刷新用户状态
   */
  const refreshAuthState = () => {
    dispatch(setUserFromStorage());
  };

  return {
    // 认证状态
    isAuthenticated,
    isLoading,
    isTokenAboutToExpire,
    token,
    userInfo,
    
    // 工具方法
    getParsedUserInfo,
    getRoles,
    checkRole,
    getUserId: getUserIdFromToken,
    isLoggedIn,
    refreshAuthState,
  };
};

/**
 * 角色检查Hook
 * @param {string|array} requiredRoles - 所需角色
 * @returns {boolean} 用户是否有指定角色
 */
export const useRoleCheck = (requiredRoles) => {
  const { checkRole } = useAuth();
  const [hasRequiredRole, setHasRequiredRole] = useState(false);

  useEffect(() => {
    setHasRequiredRole(checkRole(requiredRoles));
  }, [checkRole, requiredRoles]);

  return hasRequiredRole;
};